package com.jsmtr.rms.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.LayuiDataTableResultBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.BaseExaminer;
import com.jsmtr.rms.entity.BaseExaminerGroup;
import com.jsmtr.rms.entity.BaseUser;
import com.jsmtr.rms.entity.vo.BaseExaminers;
import com.jsmtr.rms.service.IBaseExaminerService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.MathTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/BaseExaminer")
public class BaseExaminerController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IBaseExaminerService baseExaminerService;

    //主界面
    @RequestMapping("/")
    public String Index(Model model) {
        return "/baseexaminer/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getlists")
    public void getLists(HttpServletRequest request, HttpServletResponse response, BaseExaminerGroup group) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));

            Map<String, Object> map = baseExaminerService.getBaseExaminers(page, perpage, group);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 1;
                for (BaseExaminerGroup _group : (List<BaseExaminerGroup>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + _group.getId() + "\" /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + _group.getName() + "</td></tr>");
                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='3'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/getJsonExamlists")
    public LayuiDataTableResultBean getJsonExamlists(HttpServletRequest request, HttpServletResponse response, BaseExaminerGroup group) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));

            Map<String, Object> map = baseExaminerService.getBaseExaminers(page, limit, group);

            double pageCount = (double)map.get("pageCount");

            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0){
                Object object = map.get("list");
                int num = 1;
                for (BaseExaminerGroup _group:(List<BaseExaminerGroup>) object){
                    JSONObject jsonObject = JSONObject.fromObject(_group);
                    jsonObject.put("ids", "cb_" + _group.getId());
                    jsonObject.put("id",limit * (page - 1) + num);
                    jsonObject.put("name",_group.getName());
                    jsonArray.add(jsonObject);
                    num++;
                }
            }else {

            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);

            return result;

        }catch (Exception e){
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }

    }

    //选择人员
    @RequestMapping("/selectuser")
    public String SelectUser() {
        return "/baseexaminer/selectuser";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getulists")
    public void getULists(HttpServletRequest request, HttpServletResponse response) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String key = request.getParameter("key").trim();

            Map<String, Object> map = baseExaminerService.getUsers(page, perpage, key);

            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                for (BaseUser usr : (List<BaseUser>) object) {
                    result.append("<tr><td><input type=\"checkbox\" id=\"cb_" + usr.getId() + "\" /></td>");
                    result.append("<td>" + usr.getUcode() + "</td>");
                    result.append("<td>" + usr.getUname() + "</td>");
                    result.append("<td>" + usr.getUtel() + "</td>");
                    result.append("<td>" + usr.getUdeptname() + "</td></tr>");
                }
            } else {
                result.append("<tr><td colspan='5'>无符合条件的数据</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='5'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }
    }

    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping("/getulistsLayuiJson")
    public LayuiDataTableResultBean getulistsLayuiJson(HttpServletRequest request, HttpServletResponse response) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String key = request.getParameter("key").trim();

            Map<String, Object> map = baseExaminerService.getUsers(page, limit, key);

            double pageCount = (Double) map.get("pageCount");
            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0){
                Object object = map.get("list");
                int num = 1;
                for (BaseUser user:(List<BaseUser>) object){
                    JSONObject jsonObject = JSONObject.fromObject(user);
                    jsonObject.put("ids","cb_" + user.getId());
                    jsonArray.add(jsonObject);
                    num++;
                }
            }else {

            }
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(((Double)map.get("count")).intValue());
            result.setData(jsonArray);

            return result;
        }catch (Exception e){
            e.printStackTrace();
            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //添加
    @RequestMapping("/add")
    public String Add() {
        return "/baseexaminer/add";
    }

    //添加
    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/AddAction", method = RequestMethod.POST)
    public void AddAction(HttpServletRequest request, HttpServletResponse response, BaseExaminers examiner) {
        try {
            List list = new ArrayList();
            BaseExaminerGroup group = new BaseExaminerGroup();
            String groupid = UUID.randomUUID().toString();
            group.setName(examiner.getName());
            group.setId(groupid);
            list.add(group);

            if (examiner.getExaminers() == null) {
                utilService.printJsonResult(false, "请选择人员信息", "no", response);
            } else {
                List<Integer> numerator = new ArrayList<Integer>();   //分子
                List<Integer> denominator = new ArrayList<Integer>(); //分母

                boolean flag = true;

                for (BaseExaminer exam : examiner.getExaminers()) {
                    exam.setGroupid(groupid);
                    exam.setGroupname(group.getName());
                    exam.setId(UUID.randomUUID().toString());
                    list.add(exam);

                    if (exam.getUweight().contains("/")) {
                        numerator.add(Integer.parseInt(exam.getUweight().split("/")[0].trim()));
                        denominator.add(Integer.parseInt(exam.getUweight().split("/")[1].trim()));
                    } else if (exam.getUweight().contains("%")) {
                        numerator.add(Integer.parseInt(exam.getUweight().replace("%", "").trim()));
                        denominator.add(100);
                    } else {
                        flag = false;
                        break;
                    }
                }

                if (!flag) {
                    utilService.printJsonResult(false, "评分权重格式有误！", "no", response);
                } else {
                    int weight = MathTools.fracAdd(numerator, denominator);
                    if (weight == 1) {
                        utilService.addList(list);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "评分权重之和必须等于1！", "no", response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //修改
    @RequestMapping("/edit")
    public String Edit(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            BaseExaminerGroup group = baseExaminerService.getGroup(id);
            model.addAttribute("group", group);
            List<BaseExaminer> examiners = baseExaminerService.getBaseExaminers(id);
            model.addAttribute("examiners", examiners);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/baseexaminer/edit";
    }

    //修改
    @RequestMapping(value = "/EditAction", method = RequestMethod.POST)
    public void EditAction(HttpServletRequest request, HttpServletResponse response, BaseExaminers examiner) {
        try {
            if (examiner.getExaminers() == null) {
                utilService.printJsonResult(false, "请选择人员信息", "no", response);
            } else {
                String id = request.getParameter("id").trim();
                //修改
                BaseExaminerGroup group = baseExaminerService.getGroup(id);
                group.setName(examiner.getName());
                //删除
                List<BaseExaminer> examiners = baseExaminerService.getBaseExaminers(id);

                List<Integer> numerator = new ArrayList<Integer>();   //分子
                List<Integer> denominator = new ArrayList<Integer>(); //分母

                boolean flag = true;

                //添加
                for (BaseExaminer exam : examiner.getExaminers()) {
                    exam.setGroupid(id);
                    exam.setGroupname(group.getName());
                    exam.setId(UUID.randomUUID().toString());

                    if (exam.getUweight().contains("/")) {
                        numerator.add(Integer.parseInt(exam.getUweight().split("/")[0].trim()));
                        denominator.add(Integer.parseInt(exam.getUweight().split("/")[1].trim()));
                    } else if (exam.getUweight().contains("%")) {
                        numerator.add(Integer.parseInt(exam.getUweight().replace("%", "").trim()));
                        denominator.add(100);
                    } else {
                        flag = false;
                        break;
                    }
                }

                if (!flag) {
                    utilService.printJsonResult(false, "评分权重格式有误！", "no", response);
                } else {
                    int weight = MathTools.fracAdd(numerator, denominator);
                    if (weight == 1) {
                        utilService.editList(group, examiners, examiner.getExaminers());
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "评分权重之和必须等于1！", "no", response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //删除
    @SuppressWarnings({"unchecked", "rawtypes"})
    @RequestMapping(value = "/DelAction", method = RequestMethod.POST)
    public void DelAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id").trim();
            List list = new ArrayList();
            BaseExaminerGroup group = baseExaminerService.getGroup(id);
            list.add(group);
            List<BaseExaminer> examiners = baseExaminerService.getBaseExaminers(id);
            list.addAll(examiners);

            utilService.delList(list);
            utilService.printJsonResult(true, "操作成功！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //查看
    @RequestMapping("/view")
    public String View(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            BaseExaminerGroup group = baseExaminerService.getGroup(id);
            model.addAttribute("group", group);
            List<BaseExaminer> examiners = baseExaminerService.getBaseExaminers(id);
            model.addAttribute("examiners", examiners);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/baseexaminer/view";
    }

}
